<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\personal\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
use think\Loader;
use think\facade\Config;
use library\service\AdminService;
use library\tools\Data;
use think\Validate;
/**工具**/
use app\common\Compress;
use \Yunpian\Sdk\YunpianClient;
use think\facade\Cookie;
use think\facade\Cache;
use think\facade\Log;
use redis\Redis;
use app\admin\controller\Index as adminindex;

/**
 * 个人中心管理
 * Class User
 * @package app\worker\controller
 */
class Personal extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'InvitationList';

    /**
     * 个人中心index
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {

        // $this->title = '仓库权限管理';
		 $this->title = '账户管理';
         $userinfo = $this->getGuserinfo();
         $dbconf = $this->getconfig('vister_db');
         $fetch_data = [];

         if($userinfo['db1']['authorize'] ==2 || $userinfo['db1']['authorize'] ==8){
            $where = 'id = '.$userinfo['db2']['companyid'];
            $fetch_data['companyinfo'] =  Db::connect($dbconf)->table('view_company')->where($where)->find();
            $where = 'openid = "'.$userinfo['db2']['openid'].'"';
            $fetch_data['storememberinfo'] = Db::connect($dbconf)->table('view_user_store_member')->where($where)->find();

         }
         
         $where = 'id = '.$userinfo['db1']['authorize'];
         $fetch_data['authorizeinfo'] = Db::table('system_auth')->where($where)->find(); 
         
         $this->fetch('',$fetch_data);
        // $this->_query($this->table)->like('nickname,user_type,department')->equal('status')->page();
    }
	
	
	/**
     * 上传\更新营业执照-企业管理者同时更新用户信息
     * @auth         false
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-21T15:40:49+0800
     * @LastTime     2020-10-21T15:40:49+0800
     * @return       [type]                       [description]
     * @param [type] $[name] [<description>]                 
     *         update   type    更新
     */
    public function upload(){

        // array(4) { ["title"]=> string(39) "深圳市聚艺雕塑制作有限公司" ["code"]=> string(18) "9144030035648195XH" ["local_url"]=> string(64) "http://pc.zsicp.com/upload/130eebf8537dd470/e60ab699cf65035d.jpg" ["companycardtype"]=> string(6) "update" }
            $dbconf = $this->getconfig('vister_db');
            $local_url = $this->request->param('local_url');
            $type = $this->request->param('companycardtype');
            $is_update = $this->request->param('type'); //update
            if(!$local_url && $type!="update"){$this->error('未上传营业执照');}
            if($type=='update'){
                $userinfo = $this->getGuserinfo();

                switch ($userinfo['db1']['authorize']) {
                    case '1':
                        $companyinfo = Db::connect($dbconf)->table('view_company')->where(['id' => 9999])->find();
                         $data = [
                            'name' => $this->request->param('title'),
                            'code' =>  $this->request->param('code'),
                            'imgurl' =>  $this->request->param('local_url'),
                            'examinetime' => NULL,
                            'status' =>  0,
                            'corporation' =>  $this->request->param('corporation'),
                            'address' =>  $this->request->param('address'),
                            'mobile' => $this->request->param('company_mobile')?:NULL,
                            'warrant' => $this->request->param('uploadsq'),
                        ];
                        $check = Db::connect($dbconf)->table('view_company')->where(['code' => $data['code']])->find();

                        if($check['id'] != $userinfo['db1']['companyid'] && $check['code'] == $data['code']){$this->success('信息已更新,公司已存在');}
                        $res = Db::connect($dbconf)->table('company')->where(['id' => 9999])->data($data)->update();
                        $this->success('更新营业执照成功,请耐心等待审核');
                        break;
                    case '2':
                    case '8':
                        $companyinfo = Db::connect($dbconf)->table('view_company')->where(['id' => $userinfo['db2']['companyid']])->find();
                        $company_data = [
                            'name' => $this->request->param('title'),
                            'code' =>  $this->request->param('code'),
                            'imgurl' =>  $this->request->param('local_url'),
                            'examinetime' => NULL,
                            'status' =>  0,
                            'corporation' =>  $this->request->param('corporation'),
                            'address' =>  $this->request->param('address'),
                            'mobile' => $this->request->param('company_mobile')?:NULL,
                            'warrant' => $this->request->param('uploadsq'),
                        ];
                        $check = Db::connect($dbconf)->table('view_company')->where(['code' => $company_data['code']])->find();

                        //更新用户信息
                        // $person_data = $this->_vali([
                        //     'phone.require' => '登录手机号不能为空!',
                        //     'phone.min:11'   => '登录手机号长度不能少于11位有效字符！',
                        //     'code.require' => '登录验证码不能为空！',
                        //     'code.min:6'   => '登录验证码长度不能少于6位有效字符！',
                        //     'verify.require'   => '图形验证码不能为空！',
                        //     'uniqid.require'   => '图形验证标识不能为空！',

                        //     'name' => '参数'
                        //     'sex' => '参数'
                        //     'idcard_date_type' => '参数'
                        //     'identitycard' => '参数'
                        //     'imgurl' => '参数'
                        //     'imgurl_b' => '参数'
                        //     'birthday' => '参数'
                        // ]);
                        $person_data = [
                             'name' => $this->request->param('name'),
                             'sex' => $this->request->param('sex'),
                             'identitycard' => $this->request->param('identitycard'),
                             'imgurl' => $this->request->param('uploadidcardz'),
                             'imgurl_b' => $this->request->param('uploadidcardf'),
                             'birthday' => $this->request->param('birthday'),
                             'idcard_date_type' => $this->request->param('idcarddate'),
                        ];

                        if($person_data['idcard_date_type']==='0'){
                            $person_data['idcard_date_begin'] = $this->request->param('idcard_date1');
                            $person_data['idcard_date_end'] = $this->request->param('idcard_date2');
                        }
                        if($check['id'] != $userinfo['db2']['companyid'] && $check['code'] == $company_data['code']){$this->error('公司已存在,请登录主体帐号');}
                        $res = Db::connect($dbconf)->table('company')->where(['id' => $userinfo['db2']['companyid']])->data($company_data)->update();




                        //更新用户信息
                        $pc_udata = [
                            'username' => $person_data['name']?:$company_data['mobile'],
                            // 'phone' => $company_data['mobile'],
                            //'companyid' => $userinfo['db2']['companyid'],                                
                        ];
                        $res = Db::table('system_user')->where('id = '.$userinfo['db1']['id'])->data($pc_udata)->update();
                        //$person_data['mobile'] = $company_data['mobile'];
                        //$person_data['roleid'] = 2;
                        //$person_data['companyid'] = $userinfo['db2']['companyid'];
                        $person_data['companame'] = $company_data['name']?:NULL;

                        $res = Db::connect($dbconf)->table('user')->where('id = '.$userinfo['db2']['id'])->data($person_data)->update($person_data);
                        $this->success('更新营业执照成功,请耐心等待审核');
                        # code...
                        break;
                        case '9':

// address: "zs"
// birthday: "2000-01-22"
// card_type: "居民身份证"
// code: "91442000055362789H"
// company_mobile: "15362912806"
// companycardtype: "update"
// corporation: "卢锐洪"
// idcard_date1: "2020-11-26"
// idcard_date2: "2020-11-26"
// idcarddate: "0"
// identitycard: "442000200001227152"
// local_url: undefined
// name: "梁俊杰"
// sex: "1"
// title: "广东华农农业股份有限公司"
// uploadidcardf: "http://pc.zsicp.com/upload/4980fe6ad6f34296/f29f43060a78be6e.jpg"
// uploadidcardz: "http://pc.zsicp.com/upload/f558df8e18effd35/09a9f793f4e78fd5.jpg"
// uploadsq: "http://pc.zsicp.com/upload/75fc7c16c063022d/aa8e3dbc907dba89.jpg"
// uploadyyzz: "http://pc.zsicp.com/upload/ef879733ec8e6c86/7beb2febed03c37a.jpg"

                            $company_data = [
                                'name' => $this->request->param('title'),
                                'code' =>  $this->request->param('code'),
                                'imgurl' =>  $this->request->param('uploadyyzz'),
                                'examinetime' => NULL,
                                'status' =>  0,
                                'corporation' =>  $this->request->param('corporation'),
                                'address' =>  $this->request->param('address'),
                                'mobile' => $this->request->param('company_mobile')?:NULL,
                                'warrant' => $this->request->param('uploadsq'),
                                'createuid' => $userinfo['db2']['id'],
                                'createtime'=> time(),
                            ];
                            $check = Db::connect($dbconf)->table('view_company')->where(['code' => $company_data['code']])->find();
                            //人物信息
                            $person_data = [
                                'name' => $this->request->param('name'),
                                'sex' => $this->request->param('sex'),
                                'identitycard' => $this->request->param('identitycard'),
                                'imgurl' => $this->request->param('uploadidcardz'),
                                'imgurl_b' => $this->request->param('uploadidcardf'),
                                'birthday' => $this->request->param('birthday'),
                                'idcard_date_type' => $this->request->param('idcarddate'),
                            ];
                            if($person_data['idcard_date_type']===0){
                                $person_data['idcard_date_begin'] = $this->request->param('idcard_date1');
                                $person_data['idcard_date_end'] = $this->request->param('idcard_date2');
                            }
                            if($check['code'] == $company_data['code']){$this->error('公司已存在,请登录主体帐号');}
                            $res_company = Db::connect($dbconf)->table('company')->insertGetId($company_data);
                            //更新用户信息
                            $pc_udata = [
                                'username' => $person_data['name']?:$company_data['mobile'],
                                // 'phone' => $company_data['mobile'],
                                'companyid' => $res_company,                                
                            ];
                            $res = Db::table('system_user')->where('id = '.$userinfo['db1']['id'])->data($pc_udata)->update();
                            //$person_data['mobile'] = $company_data['mobile'];
                            //$person_data['roleid'] = 2;
                            $person_data['companyid'] = $res_company;
                            $person_data['companame'] = $company_data['name']?:NULL;

                            $res = Db::connect($dbconf)->table('user')->where('id = '.$userinfo['db2']['id'])->data($person_data)->update($person_data);


                            $this->success('提交成功,请耐心等待审核');
                            # code...
                            break;
                    default:
                        $this->error("无权限操作");
                        # code...
                        break;
                }
            
                //$this->success('成功更新');

            }
            //end update


            $ai = new \Baidu_AI();
            $res = $ai->business_license_verify($local_url);

            $name = $res['words_result']['单位名称']['words'];
            $code = $res['words_result']['社会信用代码']['words'];                
            $corporation = $res['words_result']['法人']['words'];                
            $address = $res['words_result']['地址']['words'];    


            if( $name !== '无' && $code !== '无' && $corporation !== '无'&& $address !== '无' ){
                $data = ['name'=>$name , 'code'=>$code,'corporation'=>$corporation,'address'=>$address];

                $check_same = Db::connect($dbconf)->table('view_company')->where('code',$code)->find();
                if($check_same && $is_update!='update'){
                  return toJson(['message'=>'企业已存在','code'=>'400']);
                } 
				
                return toJson(['message'=>'营业执照验证成功','code'=>'200','data'=>$data,'src'=>$local_url]);
            }else{
				 $data = ['name'=>$name , 'code'=>$code,'corporation'=>$corporation,'address'=>$address];
				
                return toJson(['message'=>'营业执照验证失败','code'=>'400']);
            }

    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }
    }

	/**
	 * 查找添加时间
	 * @auth true
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public function create_at()
	{	
			$create_at=trim($this->request->param('create_at'));
			var_dump($create_at);
			$data=Db::name('InvitationList')->whereTime('create_at', 'between', $create_at)->select();
			print($create_at);
			$this->assign('data',$data);

	}
    /**
     * 更换手机号
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-30T17:17:49+0800
     * @LastTime     2020-09-30T17:17:49+0800
     * @return       [type]                       [description]
     */
    public function chphone(){
        $redis = new Redis;
        $userinfo = $this->getGuserinfo();

        $dbconf = $this->getconfig('vister_db');
        $mobile = $this->request->param('new_phone');
        //$verify_code = Cookie::get('Cookie_Message_'.$userinfo['db1']['id']);
        $verify_code = $redis::get('pc_phone_Message_'.$userinfo['db1']['id']);
        if($this->request->post()){
            if($this->request->param('yz_code')!=$verify_code){$this->error('验证码错误');}
            //check replace user phone 
            $check_replace = Db::table('system_user')->where('phone = '.$mobile)->find();
            if($check_replace){$this->error('手机号已绑定其他用户!');}
            $res = Db::table('system_user')->where(['id'=>$userinfo['db1']['id']])->data(['phone'=>$mobile])->update();
            if($userinfo['db2']!=NULL){
                $res = Db::connect($dbconf)->table('user')->where(['id'=>$userinfo['db2']['id']])->data(['mobile'=>$mobile])->update();
            }
            //Cookie::delete('Cookie_Message_'.$userinfo['db1']['id']);
            $redis::del('pc_phone_Message_'.$userinfo['db1']['id']);
            $this->app->session->clear();
            $this->app->session->destroy();
            $this->success('手机号更换成功,请重新登录', url('@admin/login'));
            // $this->success('手机号更换成功');
        }

        // $this->_form(Db::connect($dbconf)->table($this->table), 'chphone');
        $this->fetch();
    }
    /**
     * 发送验证码
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-09T10:02:28+0800
     * @LastTime     2020-10-09T10:02:28+0800
     * @return       [type]                       [description]
     */
    public function send_code(){
        $redis = new Redis;
        $userinfo = $this->getGuserinfo();
        $type = $this->request->param('c_type');//Ch_pass 
        $dbconf = $this->getconfig('vister_db');
        $mobile = $this->request->param('new_phone');
        $py_key = Db::connect($dbconf)->table('sysconfig')->where(['name'=>'Yunpian_Apikey'])->find();
        if($mobile==''){$this->error('手机号为空');}

        if($type !='Ch_pass' && $userinfo['db1']['phone']==$mobile){$this->error('手机号相同,无需重新绑定');}
        //初始化client,apikey作为所有请求的默认值
        $clnt = YunpianClient::create($py_key['val']);
        $code = mt_rand(100000,999999);

        $param = [YunpianClient::MOBILE => $mobile ,YunpianClient::TEXT => '【智服网】您的验证码是'.$code];

        try{
            $r = $clnt->sms()->single_send($param);
            if($r->isSucc()){
                if($type=='Ch_pass'){
                    $redis_str = 'pc_phone_Message_chpassword_'.$userinfo['db1']['id'];
                }else{
                    $redis_str = 'pc_phone_Message_'.$userinfo['db1']['id'];
                }
                $redis::set($redis_str,$code,1200);
                //Cookie::set('Cookie_Message_'.$userinfo['db1']['id'] ,$code,1200);
                // var_dump($r->data());
                $this->success('验证码成功发送.');
                return true;
            }else{
                $this->error('验证码发送失败.');
                return false;
            }
        }catch(Exception $e) {
            $this->error('验证码发送失败,请稍后再试.');
        }

    }

    /**
     * 更换邮箱
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-30T17:17:49+0800
     * @LastTime     2020-09-30T17:17:49+0800
     * @return       [type]                       [description]
     */
    public function chemail(){
         $dbconf = $this->getconfig('vister_db');
         $userinfo = $this->getGuserinfo();
         $mail = $this->request->param('mail');

        // $this->_form(Db::connect($dbconf)->table($this->table), 'chphone');
        if($this->request->isPost()){
         $check = c_email($mail);
         if(!$check){$this->error('请检查邮箱是否正确');}
         $data = ['mail' => $mail];
         $where = 'id = '.$userinfo['db1']['id'];
         $res = Db::table('system_user')->where($where)->data($data)->update();
         try{
            $data = ['email' => $mail];
            $where = 'id = '.$userinfo['db2']['id'];
            $res = Db::connect($dbconf)->table('user')->where($where)->data($data)->update();
         }catch(\Throwable $th) {
           Log::info('前端用户信息邮箱无法修改-对应后台用户id-'.$userinfo['db1']['id']);
        }
        $this->success('修改邮箱成功');
        }
        $this->fetch();
         
    }
	/**
     * 修改密码
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-16T16:20:11+0800
     * @LastTime     2020-11-16T16:20:11+0800
     * @return       [type]                       [description]
     */
    public function pass(){
        $this->title = '修改密码';
        $id = NULL;
        $userinfo = $this->getGuserinfo();
        $this->userinfo = $userinfo;
        if(!$id || $id == 'null'){
            $id = $userinfo['db1']['id'];
        }

        $this->applyCsrfToken();
        if (intval($id) !== intval(session('user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if (!AdminService::instance()->isLogin()) {
            $this->error('需要登录才能操作哦！');
        }
        if ($this->request->isGet()) {

            $this->verify = true;

            $this->_form('SystemUser', 'admin@user/pass', 'id', [], ['id' => $id]);
        } else {
            $redis = new Redis;
            $data = $this->_input([
                'password'    => $this->request->post('password'),
                'repassword'  => $this->request->post('repassword'),
                'oldpassword' => $this->request->post('oldpassword'),
            ], [
                // 'oldpassword' => 'require',
                'password'    => 'require|min:4',
                'repassword'  => 'require|confirm:password',
            ], [
                // 'oldpassword.require' => '旧密码不能为空！',
                'password.require'    => '登录密码不能为空！',
                'password.min'        => '登录密码长度不能少于4位有效字符！',
                'repassword.require'  => '重复密码不能为空！',
                'repassword.confirm'  => '重复密码与登录密码不匹配，请重新输入！',
            ]);
            $user = Db::name('SystemUser')->where(['id' => $id])->find();


            //$oldpassword = $this->request->param('oldpassword');
            if ($data['password'] !== $data['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            //验证码检测
            $verify_code = $redis::get('pc_phone_Message_chpassword_'.$userinfo['db1']['id']);
            if(!$verify_code){$this->error('验证码过时,请重新发送');}
            if($this->request->param('yz_code') != $verify_code){$this->error('验证码错误');}
            // if (md5($oldpassword.Config::get('salt')) !== $user['password']) {
            //     $this->error('旧密码验证失败，请重新输入！');
            // }
            if (Data::save('SystemUser', ['id' => $user['id'], 'password' => md5($oldpassword.Config::get('salt'))])) {
                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 身份证重传(实名认证)
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-24T16:02:35+0800
     * @LastTime     2020-11-24T16:02:35+0800
     * @return       [type]                       [description]
     */
    public function personverif(){
        $this->title = '实名认证';
        // array(8) { ["uploadidcardz"]=> string(64) "http://pc.zsicp.com/upload/5c89cc49eaecae40/c37bc12e7e8becd0.jpg" ["uploadidcardf"]=> string(64) "http://pc.zsicp.com/upload/9a7a3a9ea16d669a/6ca725e5662cf542.jpg" ["name"]=> string(6) "邓天" ["sex"]=> string(1) "1" ["card_type"]=> string(15) "居民身份证" ["identitycard"]=> string(18) "440921199511031217" ["birthday"]=> string(10) "1995-11-03" ["personcardtype"]=> string(6) "update" }
        // 
        if($this->request->isPost()){

            $validate = Validate::make([
                'uploadidcardz' => 'require',
                'uploadidcardf' => 'require',
                'name' => 'require',
                'sex' => 'require',
                'card_type' => 'require',
                'identitycard' => 'require',
                'birthday' => 'require',
            ]);
            
            $data = [
                'uploadidcardz' => $this->request->param('uploadidcardz'),
                'uploadidcardf' => $this->request->param('uploadidcardf'),
                'name' => $this->request->param('name'),
                'sex' => $this->request->param('sex'),
                'card_type' => $this->request->param('card_type'),
                'identitycard' => $this->request->param('identitycard'),
                'birthday' => $this->request->param('birthday'),
            ];
            if (!$validate->check($data)) {
                $this->error('参数错误','',400);
            }
            $checkid_card = isCreditNo($data['identitycard']);
            if(!$checkid_card){$this->error('身份证信息错误,请重新上传.','',400);}
            $dbconf = $this->getconfig('vister_db');
            $userinfo = $this->getGuserinfo();
            if($userinfo['db2']==NULL){$this->error('用户信息错误,请从手机端修改个人信息');}
            $udata = [
                'name' => $data['name'],
                'identitycard' => $data['identitycard'],
                'sex' => $data['sex'],
                'birthday' => $data['birthday'],
                'imgurl' => $data['uploadidcardz'],
                'imgurl_b' => $data['uploadidcardf'],
            ];
            $where = 'id = '.$userinfo['db2']['id'];
            $res = Db::connect($dbconf)->table('user')->where($where)->data($udata)->update();
            if($res){$this->success('实名认证成功','',200);}
            $this->error('实名认证失败,请稍后再试','',400);
        }
        $this->fetch();

    }
}
